import {
  getUserId,
  getToken
} from "../../utils/storage"; // 导入获取userId的方法

Page({
  data: {
    name: '',
    familyName: '',
    date: '', // 初始日期将在onLoad中动态设置
    minDate: '', // 最小可选日期（明天）
    morningActive: true,
    afternoonActive: false,
    timeList: [{
        time: '08:00',
        status: 'available'
      },
      {
        time: '08:30',
        status: 'available'
      },
      {
        time: '09:00',
        status: 'available'
      },
      {
        time: '09:30',
        status: 'available'
      },
      {
        time: '10:00',
        status: 'available'
      },
      {
        time: '10:30',
        status: 'available'
      },
      {
        time: '11:00',
        status: 'available'
      },
      {
        time: '11:30',
        status: 'available'
      },
      {
        time: '12:00',
        status: 'available'
      },
    ],
    selectedTime: '',
    familyName: '', // 选中的家人姓名
    showNameModal: false, // 弹框显示状态
    nameList: [], // 初始化为空数组，通过接口获取
    userPhone: '', // 绑定输入的手机号
    showTip: false, // 控制提示弹框显示
    userId: '' // 存储当前用户ID
  },

  onLoad() {
    const token = getToken()
    console.log('页面加载完成，开始初始化日期数据和获取家人列表');
    // 打印获取到的userId，方便调试
    const userId = getUserId();
    this.setData({
      userId
    });
    console.log('当前用户ID:', userId);

    // 调用接口获取绑定的老人姓名列表
    wx.request({
      url: `http://localhost:8080/appointment/appointment/elderName/${userId}`,
      header: {
        Authorization: `Bearer ${token}`
      },
      method: 'GET',
      success: (res) => {
        console.log('获取老人姓名接口返回：', res.data);
        if (res.data && Array.isArray(res.data.name)) {
          this.setData({
            nameList: res.data.name
          });
        } else {
          console.warn('老人姓名数据格式异常，使用默认值');
          this.setData({
            nameList: ['张三']
          }); // 兜底默认值
        }
      },
      fail: (err) => {
        console.error('获取老人姓名接口失败：', err);
        wx.showToast({
          title: '获取家人列表失败，请重试',
          icon: 'none'
        });
        this.setData({
          nameList: ['张三']
        }); // 兜底默认值
      }
    });

    // 计算最小可选日期（明天）并格式化
    const today = new Date();
    const tomorrow = new Date(today);
    tomorrow.setDate(today.getDate() + 1);
    const formatDate = (date) => {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    };
    const minDate = formatDate(tomorrow);
    this.setData({
      minDate,
      date: minDate
    });
    console.log('初始化日期完成，最小日期：', minDate, '默认选中日期：', minDate);
  },

  bindNameInput(e) {
    console.log('输入预约人姓名：', e.detail.value);
    this.setData({
      name: e.detail.value
    });
  },

  bindPhoneInput(e) {
    console.log('输入手机号：', e.detail.value);
    this.setData({
      userPhone: e.detail.value
    });
  },

  bindDateChange(e) {
    const selectedDate = e.detail.value;
    console.log('选择日期：', selectedDate);
    const {
      minDate
    } = this.data;
    const selectedTime = new Date(selectedDate).getTime();
    const minTime = new Date(minDate).getTime();
    if (selectedTime < minTime) {
      wx.showToast({
        title: '只能选择明天及以后的日期',
        icon: 'none'
      });
      this.setData({
        date: minDate
      });
      console.log('日期选择无效，已重置为最小日期：', minDate);
      return;
    }
    this.setData({
      date: selectedDate
    });
    console.log('日期选择有效，当前选中日期：', selectedDate);
  },

  switchToMorning() {
    console.log('切换到上午时段');
    this.setData({
      morningActive: true,
      afternoonActive: false,
      timeList: [{
          time: '08:00',
          status: 'available'
        },
        {
          time: '08:30',
          status: 'available'
        },
        {
          time: '09:00',
          status: 'available'
        },
        {
          time: '09:30',
          status: 'available'
        },
        {
          time: '10:00',
          status: 'available'
        },
        {
          time: '10:30',
          status: 'available'
        },
        {
          time: '11:00',
          status: 'available'
        },
        {
          time: '11:30',
          status: 'available'
        },
        {
          time: '12:00',
          status: 'available'
        },
      ]
    });
  },

  switchToAfternoon() {
    console.log('切换到下午时段');
    this.setData({
      morningActive: false,
      afternoonActive: true,
      timeList: [{
          time: '12:30',
          status: 'available'
        },
        {
          time: '13:00',
          status: 'available'
        },
        {
          time: '13:30',
          status: 'available'
        },
        {
          time: '14:00',
          status: 'available'
        },
        {
          time: '14:30',
          status: 'available'
        },
        {
          time: '15:00',
          status: 'available'
        },
        {
          time: '15:30',
          status: 'available'
        },
        {
          time: '16:00',
          status: 'available'
        },
        {
          time: '16:30',
          status: 'available'
        },
        {
          time: '17:00',
          status: 'available'
        },
        {
          time: '17:30',
          status: 'available'
        },
        {
          time: '18:00',
          status: 'available'
        }
      ]
    });
  },

  selectTime(e) {
    const time = e.currentTarget.dataset.time;
    console.log('选择时间段：', time);
    if (time === '已约满') return;
    const newTimeList = this.data.timeList.map(item => {
      if (item.time === time) {
        item.status = 'selected';
        this.setData({
          selectedTime: time
        });
      } else if (item.status === 'selected') {
        item.status = 'available';
      }
      return item;
    });
    this.setData({
      timeList: newTimeList
    });
    console.log('时间段选择完成，当前选中时间：', this.data.selectedTime);
  },

  showNameModal() {
    console.log('显示家人选择弹窗');
    this.setData({
      showNameModal: true
    });
  },

  hideNameModal() {
    console.log('隐藏家人选择弹窗');
    this.setData({
      showNameModal: false
    });
  },

  selectName(e) {
    const selectedName = e.currentTarget.dataset.name;
    console.log('选择家人：', selectedName);
    this.setData({
      familyName: selectedName,
      showNameModal: false
    });
  },

  _formatDateTime() {
    const date = new Date();
    const formatted = [
      date.getFullYear(),
      this._padZero(date.getMonth() + 1),
      this._padZero(date.getDate())
    ].join('-') + ' ' + [
      this._padZero(date.getHours()),
      this._padZero(date.getMinutes()),
      this._padZero(date.getSeconds())
    ].join(':');
    console.log('格式化当前时间：', formatted);
    return formatted;
  },

  _padZero(num) {
    return num < 10 ? '0' + num : num;
  },

  _isValidPhone(phone) {
    const reg = /^1[3-9]\d{9}$/;
    return reg.test(phone);
  },

  handleReserve() {
    console.log('开始执行预约操作');
    const {
      name,
      userPhone,
      selectedTime,
      familyName,
      date
    } = this.data;
    // 获取userId作为remark值
    const remark = getUserId();
    console.log('待提交的remark（userId）：', remark);

    // 基础校验
    if (!name) {
      console.log('预约人姓名为空，校验失败');
      return wx.showToast({
        title: '请输入预约人姓名',
        icon: 'none'
      });
    }
    if (!userPhone) {
      console.log('手机号为空，校验失败');
      return wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      });
    }
    if (!this._isValidPhone(userPhone)) {
      console.log('手机号格式错误，校验失败');
      return wx.showToast({
        title: '请输入正确的手机号格式',
        icon: 'none'
      });
    }
    if (!selectedTime) {
      console.log('未选择预约时间，校验失败');
      return wx.showToast({
        title: '请选择预约时间',
        icon: 'none'
      });
    }
    if (!familyName) {
      console.log('未选择家人，校验失败');
      return wx.showToast({
        title: '请选择家人',
        icon: 'none'
      });
    }

    console.log('基础校验通过，开始提交预约');
    wx.showLoading({
      title: '处理中...',
      mask: true
    });

    // 1. 检查手机号是否已预约
    this._checkMobile(userPhone)
      .then(() => {
        console.log('手机号校验通过，未重复预约');
        // 2. 获取老人ID
        return this._getElderId(familyName);
      })
      .then(elderId => {
        console.log('成功获取老人ID：', elderId);
        // 3. 构造预约数据（包含remark字段）
        const appointmentTime = `${date} ${selectedTime}:00`;
        console.log('构造预约时间：', appointmentTime);
        // 4. 提交预约表单（新增remark字段）
        return this._submitAppointment({
          name,
          mobile: userPhone,
          appointmentTime,
          elderId,
          appointmentType: 1,
          status: 0,
          createdAt: this._formatDateTime(),
          remark: remark // 新增remark字段，值为userId
        });
      })
      .then(() => {
        wx.hideLoading();
        console.log('预约提交成功，准备显示成功提示');
        wx.showToast({
          title: '预约成功',
          icon: 'success',
          success: () => {
            console.log('成功提示显示完成，准备跳转');
            const pages = getCurrentPages();
            console.log('当前页面栈长度：', pages.length);

            setTimeout(() => {
              console.log('开始执行跳转，目标页面路径：/pages/myAppointment/MA');
              wx.navigateTo({
                url: '/pages/myAppointment/MA',
                success: () => {
                  console.log('跳转成功！已进入目标页面');
                },
                fail: (err) => {
                  console.error('跳转失败！错误详情：', err);
                }
              });
            }, 1500);
          }
        });
      })
      .catch(errMsg => {
        wx.hideLoading();
        console.error('预约流程出错：', errMsg);
        wx.showToast({
          title: errMsg,
          icon: 'none'
        });
      });
  },

  _checkMobile(mobile) {
    console.log('开始检查手机号预约状态：', mobile);
    return new Promise((resolve, reject) => {
      wx.request({
        url: `http://localhost:8080/appointment/appointment/checkMobile/${mobile}`,
        method: 'GET',
        success: res => {
          console.log('手机号校验接口返回：', res.data);
          if (res.data?.msg === '该手机号已预约') reject('该手机号已预约');
          else if (res.data?.msg === '该手机号未预约') resolve();
          else reject('查询预约状态失败');
        },
        fail: (err) => {
          console.error('手机号校验接口调用失败：', err);
          reject('网络异常，请稍后重试');
        }
      });
    });
  },

  _getElderId(familyName) {
    console.log('开始获取老人ID，家人姓名：', familyName);
    return new Promise((resolve, reject) => {
      wx.request({
        url: `http://localhost:8080/visit/visit/elderId?name=${encodeURIComponent(familyName)}`,
        method: 'GET',
        success: res => {
          console.log('老人ID接口返回：', res.data);
          if (res.data?.data?.id !== undefined && res.data.data.id !== null) {
            resolve(res.data.data.id);
          } else {
            reject('获取老人信息失败（未找到ID）');
          }
        },
        fail: (err) => {
          console.error('老人ID接口调用失败：', err);
          reject('获取老人ID失败（网络错误）');
        }
      });
    });
  },

  _submitAppointment(formData) {
    const token = getToken()
    console.log('开始提交预约表单，数据：', formData);
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'http://localhost:8080/appointment/appointment',
        method: 'POST',
        data: formData,
        header: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`
        },
        success: res => {
          console.log('预约提交接口返回：', res.data);
          if (res.data?.code === 200) {
            resolve();
          } else {
            reject(res.data?.msg || '预约提交失败（后端处理异常）');
          }
        },
        fail: (err) => {
          console.error('预约提交接口调用失败：', err);
          reject('提交预约失败（网络错误）');
        }
      });
    });
  },

});